import Flutter
import UIKit

private enum YkPluginMesageType: String {
    
    case yk_debug_test
    case yk_alert
    case yk_start_live_activity
    case yk_stop_live_activity
    case yk_reload_widget
    case yk_update_live_activity
}

private class YkPluginMesageManager {
    
    private var systemDic:[String:(_ arguments:Any?, _ callBack:@escaping FlutterResult)->Void] = [:]
    
    func registContent(type:YkPluginMesageType, actionClosure:@escaping (_ arguments:Any, _ callBack:@escaping FlutterResult)->Void) {
        
        if (!self.systemDic.keys.contains(type.rawValue)) {
            self.systemDic[type.rawValue] = actionClosure
        }
    }
    
    func executeContent(type:String, arguments:Any?, callBack:@escaping FlutterResult) {
        if (self.systemDic.keys.contains(type)),
           let closure = self.systemDic[type]
        {
            closure(arguments, callBack)
        } else {
            callBack(FlutterMethodNotImplemented)
        }
    }
}

public class YkPlugin: NSObject, FlutterPlugin {
    
    private let messageManager = YkPluginMesageManager.init()
    
    private var channel:FlutterMethodChannel?
    
    public static func register(with registrar: any FlutterPluginRegistrar) {
        let channel = FlutterMethodChannel(name: "yk_plugin", binaryMessenger: registrar.messenger())
        let instance = YkPlugin(channel)
        registrar.addMethodCallDelegate(instance, channel: channel)
    }
    
    public override init() {
        super.init()
        
    }
    
    convenience init(_ channel:FlutterMethodChannel? = nil) {
        self.init()
        self.channel = channel
        self.registManager()
    }

  public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
    
      self.messageManager.executeContent(type: call.method, arguments: call.arguments, callBack: result)
  }
    
}

private extension YkPlugin {
    
    
    func registManager() {
        
        self.messageManager.registContent(type: .yk_debug_test) { [weak self] arguments, callBack in
#if DEBUG
            self?.channel?.invokeMethod("yk_invoked_open_url", arguments: [
                "url":"https://www.baidu.com"
            ])
            callBack("iOS " + UIDevice.current.systemVersion)
#else
            callBack(FlutterMethodNotImplemented)
#endif
        }
        
        self.messageManager.registContent(type: .yk_alert) { [weak self] arguments, callBack in
            guard let weakSelf = self else { return }
            
            if let dic = arguments as? [String:Any] {
                let title = dic["title"] ?? ""
                let msg = dic["msg"] ?? ""
                
                var comBtnText = "确定"
                if let text = dic["confirmBtnText"],
                   !(text is NSNull)
                {
                    comBtnText = "\(text)"
                }
                
                var cancelBtnText = "取消"
                
                if let text = dic["cancelBtnText"],
                   !(text is NSNull)
                {
                    cancelBtnText = "\(text)"
                }
                
                let alert = UIAlertController(title: "\(title)", message: "\(msg)", preferredStyle: .alert)
                alert.addAction(.init(title: "\(comBtnText)", style: .default, handler: { action in
                    callBack(true)
                }))
                alert.addAction(.init(title: "\(cancelBtnText)", style: .destructive, handler: { action in
                    callBack(false)
                }))
                weakSelf.topWindow.rootViewController?.present(alert, animated: true)
                
            } else {
                callBack(false)
            }
        }
        
        self.messageManager.registContent(type: .yk_start_live_activity) { arguments, callBack in
            NotificationCenter.default.post(name: NSNotification.Name.init("yk_plugin_notification"), object: nil, userInfo: [
                "name":"start_live_activity",
                "data":[
                    :
                ]
            ])
            callBack(true)
        }
        
        self.messageManager.registContent(type: .yk_stop_live_activity) { arguments, callBack in
            NotificationCenter.default.post(name: NSNotification.Name.init("yk_plugin_notification"), object: nil, userInfo: [
                "name":"stop_live_activity",
                "data":[
                    :
                ]
            ])
            callBack(true)
        }
        
        self.messageManager.registContent(type: .yk_update_live_activity) { arguments, callBack in
            
            NotificationCenter.default.post(name: NSNotification.Name.init("yk_plugin_notification"), object: nil, userInfo: [
                "name":"update_live_activity",
                "data":[
                    :
                ]
            ])
            callBack(true)
        }
        
        self.messageManager.registContent(type: .yk_reload_widget) { arguments, callBack in
            NotificationCenter.default.post(name: NSNotification.Name.init("yk_plugin_notification"), object: nil, userInfo: [
                "name":"reload_widget",
                "data":[
                    :
                ]
            ])
            callBack(true)
        }
    }
}


private extension YkPlugin {
    
    @objc private var topWindow:UIWindow {
        get {
            if #available(iOS 13.0, *) {
                if let window = UIApplication.shared.connectedScenes
                    .filter({ $0.activationState == .foregroundActive })
                    .map({ $0 as? UIWindowScene })
                    .compactMap({ $0 })
                    .last?.windows
                    .filter({ $0.isKeyWindow })
                    .last {
                    return window
                } else {
                    let window = UIApplication.shared.windows.filter({ $0.isKeyWindow }).last
                    return window ?? UIWindow()
                }
            } else {
                // Fallback on earlier versions
                return UIWindow()
            }
        }
    }
}
